package org.adream.account.service;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.adream.account.dao.UserShippingAddressDao;
import org.adream.account.entity.UserShippingAddressEntity;
import org.adream.account.model.ResultModel;
import org.adream.account.util.Constant;
import org.adream.account.util.IdGenerator;
import org.adream.account.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 用户收货地址  service
 * @author sl

	数据有效性放在controller层判断
 *
 */
@Service
public class UserShippingAddressService {
	
	private final static Logger logger = LoggerFactory.getLogger(UserShippingAddressService.class);
	
	@Autowired
	private UserShippingAddressDao addressDao;
	
	@Autowired
	private HttpSession session;
	
	/**
	 * 新增用户收货地址
	 * @param address
	 * @return
	 */
	public ResultModel<?> addAddress(UserShippingAddressEntity address) {
		logger.debug("增加用户收货地址");
		//暂定手动生成sort
		String sort = IdGenerator.getGuid();
		address.setSort(sort);
		String creatorOrModifier = !StringUtils.isEmpty((String)session.getAttribute("uid")) ? (String)session.getAttribute("uid") : address.getUid();
		address.setCreator(creatorOrModifier);
		address.setCts(new Date());
		address.setModifier(creatorOrModifier);
		address.setMts(new Date());
		address.setDr(Constant.ONE);
		
		//若新增的收货的地址为"默认收货地址",需重置之前已设置的默认收货地址
		if(address.getIsDefaultAddress() == Constant.ONE) {
			UserShippingAddressEntity defaultAddress = addressDao.queryDefaultAddress(address.getUid(), Constant.ONE, Constant.ONE);
			//之前设置过默认收货地址
			if(defaultAddress != null) {
				defaultAddress.setIsDefaultAddress(Constant.ZERO);
				defaultAddress.setModifier(creatorOrModifier);
				defaultAddress.setMts(new Date());
				int setDefaultAddressResult = addressDao.setDefaultAddress(defaultAddress);
				if(setDefaultAddressResult == Constant.ZERO) {
					logger.warn("重置默认收获地址失败,内部出错:(");
					return new ResultModel<String>(ResultModel.ERR_PARAM, "添加收货地址失败,请联系管理员", null);
				}
			}
		}
		int result = addressDao.addAddress(address);
		if(result == Constant.ZERO) {
			logger.warn("增加用户收货地址失败,内部出错:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "新增失败,请联系管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 删除用户收货地址,逻辑删除
	 * @param address
	 * @return
	 */
	public ResultModel<?> deleteAddress(String uid,String sort) {
		logger.debug("删除用户收货地址,逻辑删除");
		UserShippingAddressEntity address = addressDao.queryAddressByPkAndDr(uid, sort, Constant.ONE);
		if(address == null) {
			logger.warn("删除用户收货地址失败,未查询到相应数据:(");
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "删除失败,相关数据不存在", null);
		}
		address.setModifier(!StringUtils.isEmpty((String)session.getAttribute("uid")) 
				? (String)session.getAttribute("uid") : address.getUid());
		address.setMts(new Date());
		address.setDr(Constant.ZERO);
		int result = addressDao.deleteAddress(address);
		if(result == Constant.ZERO) {
			logger.warn("删除用户收货地址失败,内部出错:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "删除失败,请联系管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 更新用户收货地址
	 * @param address
	 * @return
	 */
	public ResultModel<?> updateAddress(UserShippingAddressEntity address) {
		logger.debug("更新用户收货地址");
		if(StringUtils.isEmpty(address.getPhone())) {
			logger.warn("更新收货地址失败,手机号为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,手机号为空", null);
		}
		//手机号是否包含*
		if(address.getPhone().indexOf("*") != -1) {
			UserShippingAddressEntity addressEntity = addressDao.queryAddressByPkAndDr(address.getUid(),address.getSort(),Constant.ONE);
			if(addressEntity == null) {
				logger.warn("更新失败,未查询到相应的收货地址");
				return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "更新失败,", null);
			}
			address.setPhone(addressEntity.getPhone());
		} else {
			//验证手机号格式
			if(!Utils.verifyPhone(address.getPhone())) {
				logger.warn("更新收货地址失败,手机号格式有误:(");
				return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,手机号格式有误", null);
			}
		}
		String modifier = !StringUtils.isEmpty((String) session.getAttribute("uid")) ? (String) session.getAttribute("uid") : address.getUid();
		address.setModifier(modifier);
		address.setMts(new Date());
		
		//若更新收货地址为"默认收货地址",需重置之前已设置的默认收货地址
		if(address.getIsDefaultAddress() == Constant.ONE) {
			UserShippingAddressEntity defaultAddress = addressDao.queryDefaultAddress(address.getUid(), Constant.ONE, Constant.ONE);
			//之前设置过默认收货地址
			if(defaultAddress != null) {
				defaultAddress.setIsDefaultAddress(Constant.ZERO);
				defaultAddress.setModifier(modifier);
				defaultAddress.setMts(new Date());
				int setDefaultAddressResult = addressDao.setDefaultAddress(defaultAddress);
				if (setDefaultAddressResult == Constant.ZERO) {
					logger.warn("重置默认收货地址失败,内部出错:(");
					return new ResultModel<String>(ResultModel.ERR_DATABASE, "更新收货地址失败,请联系管理员", null);
				}
			}
		}
		int result = addressDao.updateAddress(address);
		if(result == Constant.ZERO) {
			logger.warn("更新用户收货地址失败,内部出错:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,请联系管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 设置默认收货地址
	 * 若之前已设置的默认收货地址与当前需要设置的默认收货地址不一致,
	 * 需要设置之前的默认收货地址为非默认地址
	 * @param address
	 * @return
	 */
	public ResultModel<?> setDefaultAddress(String uid, String sort) {
		logger.debug("设置用户默认收货地址");
		UserShippingAddressEntity address = addressDao.queryAddressByPkAndDr(uid, sort, Constant.ONE);
		if(address == null) {
			logger.warn("设置默认收货地址失败,相关数据不存在:(");
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "设置失败,收货地址不存在", null);
		}
		String creatorOrModifier = !StringUtils.isEmpty((String) session.getAttribute("uid")) ? (String) session.getAttribute("uid") : uid;
		UserShippingAddressEntity defaultAddress = addressDao.queryDefaultAddress(uid, Constant.ONE, Constant.ONE);
		//是否之前已设置过"默认地址"且与当前需要设置的收货地址不一致
		if(defaultAddress != null && !defaultAddress.getSort().equals(sort)) {
			defaultAddress.setIsDefaultAddress(Constant.ZERO);
			defaultAddress.setModifier(creatorOrModifier);
			defaultAddress.setMts(new Date());
			int setDefaultAddressResult = addressDao.setDefaultAddress(defaultAddress);
			if(setDefaultAddressResult == Constant.ZERO) {
				logger.warn("重置默认收获地址失败,内部出错:(");
				return new ResultModel<String>(ResultModel.ERR_PARAM, "设置收货地址失败,请联系管理员", null);
			}
		}
		address.setModifier(creatorOrModifier);
		address.setMts(new Date());
		address.setIsDefaultAddress(Constant.ONE);
		int result = addressDao.setDefaultAddress(address);
		if(result == Constant.ZERO) {
			logger.warn("设置默认收货地址失败,内部出错:(");
			return new ResultModel<String>(ResultModel.ERR_DATABASE, "设置收货地址失败,请联系管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 根据删除标志查询收货地址
	 * @param dr	删除标志
	 * @return
	 */
	public ResultModel<?> queryAddressesByDr(Integer dr) {
		logger.warn("根据删除标志查询收货地址");
		List<UserShippingAddressEntity> addresses = addressDao.queryAddressesByDr(dr);
		if(addresses == null || addresses.size() == Constant.ZERO) {
			logger.warn("查询失败,未查询到相应数据:(");
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "查询失败,未查询到相应数据", null);
		}
		return new ResultModel<List<UserShippingAddressEntity>>(ResultModel.SUCCESS, "查询成功", addresses);
	}
	
	/**
	 * 根据uid,删除标志查询收货地址
	 * @param uid
	 * @param dr
	 * @return
	 */
	public ResultModel<?> queryAddressesByUidAndDr(String uid,Integer dr) {
		logger.debug("根据uid,删除标志查询收货地址");
		List<UserShippingAddressEntity> addresses = addressDao.queryAddressesByUidAndDr(uid, dr);
		if(addresses == null || addresses.size() == Constant.ZERO) {
			logger.warn("查询失败,未查询到相应数据:(");
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "查询失败,未查询到相应数据", null);
		}
		return new ResultModel<List<UserShippingAddressEntity>>(ResultModel.SUCCESS, "查询成功", addresses);
	}
	
	/**
	 * 根据uid,排序,删除标志查询收货地址
	 * @param uid
	 * @param sort
	 * @param dr
	 * @return
	 */
	public ResultModel<?> queryAddressByPkAndDr(String uid,String sort,Integer dr) {
		logger.debug("根据uid,排序,删除标志查询收货地址");
		UserShippingAddressEntity address = addressDao.queryAddressByPkAndDr(uid, sort, dr);
		if(address == null) {
			logger.warn("查询失败,未查询到相应数据:(");
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "查询失败,未查询到相应数据", null);
		}
		return new ResultModel<UserShippingAddressEntity>(ResultModel.SUCCESS, "查询成功", address);
	}
	
	/**
	 * 统计用户收货地址个数
	 * @param uid	user id
	 * @param dr	删除标志
	 * @return
	 */
	public ResultModel<?> countAddressesByUidAndDr(String uid, Integer dr) {
		logger.debug("统计用户收货地址个数");
		Integer count = addressDao.countAddressesByUidAndDr(uid, dr);
		return new ResultModel<Integer>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, count);
	}

	/**
	 * 新增/更新用户收货地址
	 * @param address	收货地址
	 * @return
	 */
	public ResultModel<?> saveOrUpdateAddress(UserShippingAddressEntity address) {
		logger.debug("增加或更新用户收货地址");
		if (StringUtils.isEmpty(address.getPhone())) {
			logger.warn("增加或更新用户收货地址失败,手机号为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败,手机号为空", null);
		}
		String creatorAndModifier = address.getUid();
		address.setModifier(creatorAndModifier);
		address.setMts(new Date());
		address.setDr(Constant.ONE);
		//判断sort是否为空,是:新增操作(需手动生成sort),否:更新操作
		if(StringUtils.isEmpty(address.getSort())) {
			//验证手机号码格式
			if (!Utils.verifyPhone(address.getPhone())) {
				logger.warn("增加用户收货地址失败,手机号码格式有误:(");
				return new ResultModel<String>(ResultModel.WARN_PHONE, "操作失败,手机号码格式有误", null);
			}
			address.setSort(IdGenerator.getGuid());
			address.setCreator(creatorAndModifier);
			address.setCts(new Date());
		} else {
			UserShippingAddressEntity addressEntity = addressDao.queryAddressByPkAndDr(address.getUid(), address.getSort(), Constant.ONE);
			if(addressEntity == null) {
				logger.warn("更新失败,未查询到相应的收货地址:(");
				return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "操作失败", null);
			}
			//手机号码是否包含*
			if(address.getPhone().indexOf("*") != -1) {
				//使用之前填写的手机号码进行填充
				address.setPhone(addressEntity.getPhone());
			} else {
				//验证手机号码格式
				if (!Utils.verifyPhone(address.getPhone())) {
					logger.warn("更新用户收货地址失败,手机号码格式有误:(");
					return new ResultModel<String>(ResultModel.WARN_PHONE, "操作失败,手机号码格式有误", null);
				}
			}
			address.setCreator(addressEntity.getCreator());
			address.setCts(addressEntity.getCts());
		}
		
		//若新增或更新的收货地址为"默认收货地址",需重置之前已设置的默认收货地址
		if(address.getIsDefaultAddress() == Constant.ONE) {
			UserShippingAddressEntity defaultAddress = addressDao.queryDefaultAddress(address.getUid(), Constant.ONE, Constant.ONE);
			//之前设置过默认收货地址
			if(defaultAddress != null) {
				defaultAddress.setIsDefaultAddress(Constant.ZERO);
				defaultAddress.setModifier(creatorAndModifier);
				defaultAddress.setMts(new Date());
				int setDefaultAddressResult = addressDao.setDefaultAddress(defaultAddress);
				if(setDefaultAddressResult == Constant.ZERO) {
					logger.warn("重置默认收货地址失败,内部出错:(");
					return new ResultModel<String>(ResultModel.ERR_DATABASE, "操作失败,请联系管理员", null);
				}
			}
		}
		int result = addressDao.replaceAddress(address);
		if(result == Constant.ZERO) {
			logger.warn("replace收货地址失败,内部错误:(");
			return new ResultModel<String>(ResultModel.ERR_DATABASE, "操作失败,请联系管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
}